<script>
import socketService from '@/utils/socket.js';
import useStorage from '@/utils/useStorage.js';
import { getUserInfo } from '@/utils/api.js';
// #ifdef APP
import { queryBatteryOptimizeStatus, requestIgnoreBatteryOptimization, startForegroundService, stopForegroundService } from '@/uni_modules/hr-persist-track';
// #endif
export default {
	globalData: {
		// #ifdef MP-WEIXIN
		menubar: { ...uni.getMenuButtonBoundingClientRect(), paddingBottom: 8 }
		// #endif
	},
	async onLaunch() {
		try {
			// #ifdef APP
			queryBatteryOptimizeStatus().then((isIgnoring) => {
				if (isIgnoring) {
					console.log('应用当前忽略电池优化');
					startForegroundService();
				} else {
					console.log('应用当前未忽略电池优化');
					requestIgnoreBatteryOptimization().then((result) => {
						if (result) {
							console.log('用户允许忽略电池优化');
							useStorage.set('batterFlag', true);
							startForegroundService();
						} else {
							console.log('用户未允许忽略电池优化');
						}
					});
				}
			});

			// 直接获取定位，自动弹出授权弹窗
			uni.getLocation({
				type: 'wgs84',
				success: function (res) {
					console.log('当前位置：', res);
				},
				fail: function (err) {
					// 失败时引导用户去设置
					uni.showModal({
						title: '提示',
						content: '需要获取您的位置信息，请在设置中授权',
						success(res) {
							if (res.confirm) {
								uni.openSetting();
							}
						}
					});
				}
			});
			// #endif

			let token = useStorage.get('token');
			if (token) {
				const userInfo = await getUserInfo();
				useStorage.set('userInfo', userInfo.account);
				socketService.initSocket();
			} else {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		} catch (error) {
			console.log(error);
		}
	},
	async onShow() {
		// #ifdef MP-WEIXIN
		// console.log('App Show');
		const updateManager = uni.getUpdateManager();

		updateManager.onCheckForUpdate(function (res) {
			// 请求完新版本信息的回调
			// console.log(res.hasUpdate);
		});

		updateManager.onUpdateReady(function (res) {
			updateManager.applyUpdate();
		});

		updateManager.onUpdateFailed(function (res) {
			// 新的版本下载失败
		});
		// #endif
	},
	onHide() {
		// console.log('App Hide');
	}
};
</script>

<style lang="scss">
@import '@/uni.scss';
page,
view,
text,
input,
image,
map,
video {
	box-sizing: border-box;
}
image {
	width: 100%;
	display: block;
}
page {
	font-size: $font-size;
	color: #000;
	background-color: $bg-color;
}
text {
	font-size: $font-size;
}
</style>
